package com.alks.function.service.serviceImpl.finance.fincons;


import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcCuttingSalary;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.finance.fincons.LotNoDto;
import com.alks.function.data.dto.finance.fincons.LotNoPriceDetailDto;
import com.alks.function.data.dto.finance.salary.SalaryStitchInventoryDto;
import com.alks.function.data.request.finance.fincons.LotNoCheckRequest;
import com.alks.function.data.request.finance.fincons.OrderUnitPriceRequest;
import com.alks.function.mapper.chengKong.CostAssignmentMapper;
import com.alks.function.mapper.chengKong.PcStitchProdDetailMapper;
import com.alks.function.mapper.finance.fincons.OrderUnitPriceMapper;
import com.alks.function.mapper.finance.salary.SalaryFileCreationMapper;
import com.alks.function.mapper.finance.salary.SalaryStitchInventoryMapper;
import com.alks.function.service.finance.fincons.OrderUnitPriceService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderUnitPriceServiceImpl implements OrderUnitPriceService {

    @Autowired
    private OrderUnitPriceMapper orderUnitPriceMapper;

    @Autowired
    private CostAssignmentMapper  costAssignmentMapper;

    @Autowired
    private PcStitchProdDetailMapper pcStitchProdDetailMapper;

    @Autowired
    private SalaryStitchInventoryMapper salaryStitchInventoryMapper;

    @Autowired
    private SalaryFileCreationMapper salaryFileCreationMapper;


    /**
     * 指令查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getLotNoList(OrderUnitPriceRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        //史倩待完成 派工日期
        List<LotNoDto> list = orderUnitPriceMapper.getLotNoListByView(companyId,request);

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    /**
     * 指令单价明细查询
     * @param request
     * @return
     */
    @Override
    //@AutoPageAop
    public ResponseInfo getLotNoPriceDetail(OrderUnitPriceRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<LotNoPriceDetailDto> list = orderUnitPriceMapper.getLotNoPriceDetailByView(companyId,request);

        LotNoPriceDetailDto countDto = orderUnitPriceMapper.getLotNoPriceDetailCountByView(companyId,request);

        String  count = null;
        String  countCutLayer = null;
        if(countDto != null){
             count = String.format("%.4f", countDto.getPrice());
             countCutLayer = String.format("%.4f", countDto.getCutLayer());
        }

        HashMap map = new HashMap<>();
        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        map.put("count",count);
        map.put("countCutLayer",countCutLayer);
        return ResponseInfo.ok(map);
    }

    /**
     * 导出
     * @param request
     * @param response
     */
    @Override
    public void ExportLotNoList(OrderUnitPriceRequest request, HttpServletResponse response)  throws IOException {
        String companyId = UserIdThread.get().getCompanyId();
        List<LotNoDto> list = orderUnitPriceMapper.getLotNoListByView(companyId,request);
        ExcelUtils.creatByTemplate(response,"指令单价明细模板.xls","指令单价明细_"+ DateUtils.dateTimeNow(),list);
    }

    /**
     * 检核
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo checkLotNoUnitPrice(LotNoCheckRequest request) {
        //判断
        String companyId = UserIdThread.get().getCompanyId();
        List<LotNoDto> lotNoList = request.getLotNoList();
        //检查操作是否合理
        boolean b = lotNoList.stream().anyMatch(dto -> "Y".equals(dto.getCfmFlag()));
        boolean c = lotNoList.stream().anyMatch(dto -> dto.getCfmFlag() == null);
        if (request.getCheckFlag() == 1 && b) {
            throw new ServiceErrorException("存在已检核的指令，请检查！");
        }
        if(request.getCheckFlag() == 2 && c){
            throw new ServiceErrorException("存在未检核的指令，请检查！");
        }
        if (ObjectUtils.isEmpty(lotNoList)) {
            throw new ServiceErrorException("请选择指令");
        }
        //if (lotNoList.size() > 40) {
        //    throw new ServiceErrorException("批处理最多40条指令，请检查！");
        //}
        //取消检核：取消什么类型的指令就取消什么指令结算
        // // 几个存在件资已经结算的指令，请检查！
        if (request.getCheckFlag() == 2) {
            List<String> stitchLotList = new ArrayList<>();
            List<String> cutLotList = new ArrayList<>();
            List<String> manualLotList = new ArrayList<>();
            for (LotNoDto lotNoDto : lotNoList) {
                if ("针车".equals(lotNoDto.getType())) {
                    stitchLotList.add(lotNoDto.getLotNo());
                }else if("手工".equals(lotNoDto.getType())){
                    manualLotList.add(lotNoDto.getLotNo());
                }else if("冲裁".equals(lotNoDto.getType())){
                    cutLotList.add(lotNoDto.getLotNo());
                }else{
                    throw new ServiceErrorException("指令类型传参不正确！");
                }
            }

            String mesg = "！";
            //获取针车的指令
            if(ObjectUtils.isNotEmpty(stitchLotList)){
                List<SalaryStitchInventoryDto> stitchList = salaryStitchInventoryMapper.queryLotDetails(companyId,stitchLotList);
                if(ObjectUtils.isNotEmpty(stitchList)){
                    mesg += "针车："+ String.join(",",stitchLotList) + "；";
                }
            }

            //获取冲裁的指令
            if(ObjectUtils.isNotEmpty(cutLotList)){
                List<PcCuttingSalary> cutList = salaryFileCreationMapper.queryLotDetails(companyId,cutLotList,"冲裁");
                if(ObjectUtils.isNotEmpty(cutList)){
                    mesg += "冲裁："+ String.join(",",cutLotList) + "；";
                }
            }

            //获取手工的指令
            if(ObjectUtils.isNotEmpty(manualLotList)){
                List<PcCuttingSalary> manualList = salaryFileCreationMapper.queryLotDetails(companyId,manualLotList,"手工");
                if(ObjectUtils.isNotEmpty(manualList)){
                    mesg += "手工："+ String.join(",",manualLotList) + "；";
                }
            }

            if(!mesg.equals("！")){
                throw new ServiceErrorException("存在件资已经结算的指令，请检查" + "\n" +mesg);
            }
        }

        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        for (LotNoDto lotNoDto : lotNoList) {
            String type = lotNoDto.getType();
            if(request.getCheckFlag() == 1){
                lotNoDto.setCfmFlag("Y");
                lotNoDto.setCfmDate(DateUtils.getNowDate());
                lotNoDto.setCfmUser(UserIdThread.get().getUserName());
            }else{
                lotNoDto.setCfmFlag(null);
                lotNoDto.setCfmDate(null);
                lotNoDto.setCfmUser(null);
            }
            if(type.equals("冲裁")){
                LotNoDto lot1 = costAssignmentMapper.queryPcCutLotPriceDetail(companyId, lotNoDto);
                if (lot1 != null) {
                    count1 = costAssignmentMapper.updatePcCutLotPriceDetail(companyId, lotNoDto);
                }
            }else if(type.equals("手工")){
                LotNoDto lot2 = costAssignmentMapper.queryPcCutLotPriceDetailO(companyId, lotNoDto);
                if (lot2 != null) {
                    count2 = costAssignmentMapper.updatePcCutLotPriceDetailO(companyId, lotNoDto);
                }
            }else if(type.equals("针车")){
                LotNoDto lot3 = pcStitchProdDetailMapper.queryPcStitchLotPriceDetail(companyId, lotNoDto);
                if (lot3 != null) {
                    count3 = pcStitchProdDetailMapper.updatePcStitchLotPriceDetail(companyId, lotNoDto);
                }
            }
        }

        if (count1 > 0 || count2 > 0 || count3 > 0) {
            if (request.getCheckFlag() == 1) {
                return ResponseInfo.ok("检核成功");
            }else{
                return ResponseInfo.ok("取消检核成功");
            }
        }else{
            throw new ServiceErrorException("操作失败");
        }

    }
}